{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Trigger Pipeline with Lamdba"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Set up S3 Bucket with CloudTrail API Logging\n",
    "1. Create Lambda Function to start Pipeline Execution (update Lambda w/ Pipeline Name as environment variable)\n",
    "1. Set up EventBridge Rules\n",
    "1. Trigger"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Lambda Function"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "import json\n",
    "import os\n",
    "import time\n",
    "import sys\n",
    "from pip._internal import main\n",
    "\n",
    "main(['install', '-I', '-q', 'boto3==1.16.47', '--target', '/tmp/', '--no-cache-dir', '--disable-pip-version-check'])\n",
    "sys.path.insert(0,'/tmp/')\n",
    "\n",
    "import boto3\n",
    "\n",
    "region = boto3.Session().region_name\n",
    "s3 = boto3.client('s3', region_name=region)\n",
    "sm = boto3.client('sagemaker', region_name=region)\n",
    "\n",
    "# Need to set the Pipeline Name as Lambda environment variable\n",
    "PIPELINE_NAME = os.environ['PIPELINE_NAME']\n",
    "print('Pipeline Name: {}'.format(PIPELINE_NAME))\n",
    "\n",
    "timestamp = int(time.time())\n",
    "\n",
    "def lambda_handler(event, context):\n",
    "    print('boto3: {}'.format(boto3.__version__))\n",
    "    print('Starting execution of pipeline {}...'.format(PIPELINE_NAME))\n",
    "    \n",
    "    response = sm.start_pipeline_execution(\n",
    "        PipelineName=PIPELINE_NAME,\n",
    "        PipelineExecutionDisplayName='trigger-{}'.format(timestamp),\n",
    "        PipelineParameters=[\n",
    "        ],\n",
    "        PipelineExecutionDescription= PIPELINE_NAME,\n",
    "        # ClientRequestToken='string'\n",
    "    )\n",
    "    \n",
    "    print('Response: {}'.format(response))\n",
    "    \n",
    "    execution_arn=response['PipelineExecutionArn']\n",
    "    print('Pipeline execution started with execution ARN: {}'.format(execution_arn))\n",
    "    print('Done.')\n",
    "    \n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_python3",
   "language": "python",
   "name": "conda_python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
